package com.ld.admin.service.usercenter;

import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Service;

import com.ld.admin.model.usercenter.SysUserCalendarModel;
import com.ld.shieldsb.common.composition.util.ConvertUtil;
import com.ld.shieldsb.common.composition.util.PKUtil;
import com.ld.shieldsb.common.core.collections.ListUtils;
import com.ld.shieldsb.common.core.model.Result;
import com.ld.shieldsb.common.core.reflect.ModelUtil;
import com.ld.shieldsb.common.core.util.DateUtil;
import com.ld.shieldsb.common.core.util.StringUtils;
import com.ld.shieldsb.common.web.StaticParams;
import com.ld.shieldsb.common.web.util.Web;
import com.ld.shieldsb.dao.model.PageNavigationBean;
import com.ld.shieldsb.dao.model.QueryModel;

/**
 * 
 * 用户日历服务类，@Service注解用于自动注入
 * 
 * @ClassName SysUserCalendarService
 * @author <a href="mailto:donggongai@126.com" target="_blank">吕凯</a>
 * @date 2019年02月21日 14:32:08
 *
 */
@Service
public class SysUserCalendarService extends UserCenterBasicService {

    // 用于子类覆盖，扩展doSearch方法中QueryModel的处理（标准queryModel处理完，查询进行前的处理）
    @Override
    protected QueryModel extendDealQuery(QueryModel queryModel) {
        // TODO Auto-generated method stub
        return super.extendDealQuery(queryModel);
    }

    // 用于子类覆盖，扩展doSearch方法中PageNavigationBean的处理（查询完成后进行）
    @Override
    protected <T> PageNavigationBean<T> extendDealPageNavigationBean(PageNavigationBean<T> pageNavigationBean) {
        // TODO Auto-generated method stub
        return super.extendDealPageNavigationBean(pageNavigationBean);
    }

    // 删除方法子类扩展（删除完成后进行）
    @Override
    protected <T> boolean extendRemove(Boolean flag, Class<T> classOfT, String key, Object value, Integer status, Long userId) {
        // TODO Auto-generated method stub
        return flag;
    }

    // AddOrUpdate扩展（AddOrUpdate方法完成后进行）
    @Override
    protected <T> boolean extendAddOrUpdate(Boolean flag, T modelBean, boolean update, String key, Long userId) {
        // TODO Auto-generated method stub
        return flag;
    }

    @Override
    public <T> Result addOrUpdate(T modelBean, boolean update) {
        SysUserCalendarModel model = (SysUserCalendarModel) modelBean;
        if (model.getCid() == null && model.getId() == null) {
            model.setCid(PKUtil.nextId());
        }
        String startTimeStr = getString("sDate");
        if (getString("sTime") != null) {
            startTimeStr += " " + getString("sTime");
            startTimeStr = startTimeStr.trim();
        }
        String endTimeStr = getString("eDate");
        if (getString("eTime") != null) {
            endTimeStr += " " + getString("eTime");
            endTimeStr = endTimeStr.trim();
        }
        model.setStartTime(DateUtil.str2Date(startTimeStr, startTimeStr.length() == 10 ? "yyyy-MM-dd" : "yyyy-MM-dd HH:mm"));
        model.setEndTime(DateUtil.str2Date(endTimeStr, endTimeStr.length() == 10 ? "yyyy-MM-dd" : "yyyy-MM-dd HH:mm"));
        Result result = null;
        if (model.getRepeatType() == 1) { // 重复事件
            result = saveRepeatEvents(model);
        } else { // 一次性事件
            result = super.addOrUpdate(model, model.getId() != null);
        }
        return result;
    }

    private Result saveRepeatEvents(SysUserCalendarModel model) {
        Result result = new Result();
        result = super.addOrUpdate(model, model.getId() != null);

        QueryModel queryAll = new QueryModel();
        queryAll.addEq("cid", model.getCid());
        queryAll.setOrder("startTime", false);
        queryAll.addUnEq("id", model.getId()); // 排除自己
        List<SysUserCalendarModel> calendarModels = getList(SysUserCalendarModel.class, queryAll);
        List<SysUserCalendarModel> removeModels = ListUtils.getCopyList(calendarModels);

        int frequency = model.getFrequency();
        int repeatUnit = model.getRepeatUnit();
        int repataTimes = model.getRepataTimes();
        Date startdate = model.getStartTime();
        Date enddate = model.getEndTime();
        Calendar calstart = Calendar.getInstance();
        calstart.setTime(startdate);
        Calendar calend = Calendar.getInstance();
        if (enddate != null)
            calend.setTime(enddate);
        int days = frequency;
        int senddatatype = Calendar.DAY_OF_MONTH;
        if (repeatUnit == 1) {// 天
            senddatatype = Calendar.DAY_OF_MONTH;
        } else if (repeatUnit == 2) {// 周
            senddatatype = Calendar.DAY_OF_MONTH;
            days *= 7;
        } else if (repeatUnit == 3) {// 月
            senddatatype = Calendar.MONTH;
        } else if (repeatUnit == 4) {// 年
            senddatatype = Calendar.YEAR;
        }
        for (int i = 0; i < repataTimes; i++) {
            SysUserCalendarModel ucobj = new SysUserCalendarModel();
            ModelUtil.coptyModel(model, ucobj);
            ucobj.setId(null);
            ucobj.setCid(model.getCid());
            calstart.set(senddatatype, calstart.get(senddatatype) + days);
            ucobj.setStartTime(calstart.getTime());
            if (enddate != null) {
                calend.set(senddatatype, calend.get(senddatatype) + days);
                ucobj.setEndTime(calend.getTime());
            }
            SysUserCalendarModel calendarModelHave = null;
            for (SysUserCalendarModel checkModel : calendarModels) {
                if (DateUtil.isSameDate(checkModel.getStartTime(), ucobj.getStartTime())
                        && DateUtil.isSameDate(checkModel.getEndTime(), ucobj.getEndTime())) {
                    calendarModelHave = checkModel;
                    removeModels.remove(checkModel); // 移除
                    break;
                }

            }
            if (calendarModelHave != null) { // 更新
                ModelUtil.coptyModel(ucobj, calendarModelHave);
                calendarModelHave.setState(StaticParams.STATE_NORMAL);
                super.addOrUpdate(calendarModelHave, true);
            } else { // 保存
                super.addOrUpdate(ucobj, false);
            }
        }
        for (SysUserCalendarModel checkModel : removeModels) {
            log.warn("===移除日历事件====：" + checkModel);
            super.del(SysUserCalendarModel.class, checkModel.getId());
        }
        return result;
    }

    /**
     * 获取菜单数据，数据格式为json格式
     * 
     * @Title getMenusData
     * @author 吕凯
     * @date 2019年1月14日 上午11:42:32
     * @param request
     * @return Result
     */
    public Result getCalendarData(HttpServletRequest request) {
        QueryModel queryModel = getSearchQueryModel(request);
        String start = getString("start");
        String end = getString("end");
        Result result = new Result();
        List<Map<String, String>> listMap = new ArrayList<>();
        if (StringUtils.isNotBlank(start) && StringUtils.isNotBlank(end)) {

            QueryModel queryModel1 = new QueryModel(); // start--(start-event)---end -- (end-event)
            queryModel1.addGe("startTime", DateUtil.str2Date(start));
            QueryModel queryModel2 = new QueryModel(); // (start-event) -- start--(end-event)---end
            queryModel2.addLe("endTime", DateUtil.str2Date(end));
            QueryModel queryModel3 = new QueryModel(); // start-event -- start-end -- end-event
            queryModel3.addLe("startTime", DateUtil.str2Date(start));
            queryModel3.addGe("endTime", DateUtil.str2Date(end));
            queryModel.addOrMultiCondition(queryModel1, queryModel2);

            queryModel.addEq("createBy", Web.Util.getSessionUserId(request)); // 自己
            List<SysUserCalendarModel> list = getAll(SysUserCalendarModel.class, queryModel);
            if (ListUtils.isNotEmpty(list)) {
                list.stream().forEach(model -> {
                    Map<String, String> dataMap;
                    try {
                        dataMap = ConvertUtil.obj2Map(model);
                        dataMap.put("backgroundColor", model.getBgcolor());
                        dataMap.put("oid", model.getId() + "");
                        dataMap.put("id", model.getCid() + "");
                        dataMap.put("start", remove0Time(DateUtil.getDateTimeString(model.getStartTime())));
                        if (model.getEndTime() != null) {
                            dataMap.put("end", remove0Time(DateUtil.getDateTimeString(model.getEndTime())));
                        }
                        listMap.add(dataMap);
                    } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
                        log.error("", e);
                    }
                });
            }

        }
        result.setData(listMap);
        result.setSuccess(true);
        return result;
    }

    /**
     * 移除最后的00
     * 
     * @Title remove0Time
     * @author 吕凯
     * @date 2019年2月21日 下午5:16:25
     * @param time
     * @return String
     */
    public String remove0Time(String time) {
        if (time != null && time.endsWith(":00")) {
            time = StringUtils.substringBeforeLast(time, ":00");
            return remove0Time(time);
        } else if (time != null && time.endsWith(" 00")) {
            time = StringUtils.substringBeforeLast(time, " 00");
            return remove0Time(time);
        }
        return time;
    }

}
